import xml.sax

from Learn.xml.Movie import Movie


class MovieHandler(xml.sax.handler.ContentHandler):
    def __init__(self):
        super().__init__()
        self.currentData = ""
        self.title = ""
        self.type = ""
        self.format = ""
        self.year = ""
        self.rating = ""
        self.stars = ""
        self.description = ""
        self.content = ""
        self.items = []
        self.item = {}

    def startElement(self, tag, attributes):
        self.currentData = tag
        if tag == "movie":
            print("*****Movie*****")
            title = attributes["title"]
            print("Title:", title)
            self.title = title

    def endElement(self, tag):
        if self.currentData == "type":
            print("Type: ", self.type)
        elif self.currentData == "format":
            print("Format: ", self.format)
        elif self.currentData == "year":
            print("Year: ", self.year)
        elif self.currentData == "rating":
            print("Rating: ", self.rating)
        elif self.currentData == "stars":
            print("Starts: ", self.stars)
        elif self.currentData == "description":
            print("Description: ", self.description)
        if tag == 'movie':
            self.items.append(self.item)
            self.item = {}
        else:
            self.item.update({self.currentData: self.content})

    def characters(self, content):
        if self.currentData == "type":
            self.type = content
        elif self.currentData == "format":
            self.format = content
        elif self.currentData == "year":
            self.year = content
        elif self.currentData == "rating":
            self.rating = content
        elif self.currentData == "stars":
            self.stars = content
        elif self.currentData == "description":
            self.description = content
        self.content = content

    def endDocument(self):
        global contents
        contents = self.items


contents = []

if __name__ == '__main__':
    parser = xml.sax.make_parser()
    parser.setFeature(xml.sax.handler.feature_namespaces, 0)
    Handler = MovieHandler()
    parser.setContentHandler(Handler)
    parser.parse("movies.xml")

    print("--------------------")
    movies = []
    for con in contents:
        movie = Movie()
        movie.__dict__ = con
        movies.append(movie)
    for mov in movies:
        print(mov.__dict__)

